import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Like, Repository } from 'typeorm';
import {
  BrandAdminCreateDto,
  BrandAdminIndexDto,
  BrandAdminUpdateDto,
} from './brand.dto';
import { BrandModel } from './brand.model';
import { BizFailedException } from "@/common/biz-failed/biz-failed.exception";
import { BizFailedCodeEnum } from "@/common/biz-failed/biz-failed.enum";
import { omitUndefined } from "@/common/utils/utils";
import { EvaluationModel } from "@/module/evaluation/evaluation.model";

@Injectable()
export class BrandService {
  constructor(
    @InjectRepository(BrandModel)
    private readonly brandModelRepository: Repository<BrandModel>,
    @InjectRepository(EvaluationModel)
    private readonly evaluationModelRepository: Repository<EvaluationModel>,
  ) {}

  async all(): Promise<BrandModel[]> {
    return this.brandModelRepository.createQueryBuilder('brand')
      .select([
        'brand.uuid',
        'brand.title',
        'brand.img',
        'brand.desc',
      ])
      .where('brand.status = 1')
      .orderBy({
        [`brand.title collate "zh_CN.utf8"`]: 'ASC',
        'brand.id': 'DESC',
      }).getMany();
  }

  async adminIndex(query: BrandAdminIndexDto) {
    const qb = this.brandModelRepository.createQueryBuilder('brand')
      .select([
        'brand.uuid',
        'brand.title',
        'brand.img',
        'brand.desc',
        'brand.createTime',
        'brand.updateTime',
      ])

    if (query.title) {
      qb.andWhere('brand.title ILIKE :title',{
        title: `%${query.title}%`,
      });
    }

    if(!!query.enableTitleSort){
      qb.addOrderBy(`brand.title collate "zh_CN.utf8"`, 'ASC')
    }

    qb.addOrderBy('brand.id', 'DESC')

    return qb.getManyAndCount();
  }

  async adminCreate(body: BrandAdminCreateDto): Promise<void> {
    await this.brandModelRepository.save({
      ...body,
    });
  }

  async adminUpdate(body: BrandAdminUpdateDto, uuid: string): Promise<void> {
    await this.brandModelRepository.update(
      {
        uuid,
      },
      omitUndefined(body),
    );
  }

  async adminDestroy(uuid: string): Promise<void> {
    const count = await this.evaluationModelRepository.count({
      where: {
        brandUuid: uuid,
      }
    });
    if(count){
      throw new BizFailedException(BizFailedCodeEnum.BRAND_USED_BY_EVALUATION);
    }
    await this.brandModelRepository.delete({
      uuid,
    });
  }
}
